import * as multer from 'multer';
import * as fs from 'fs';
import * as path from 'path';
import { format } from 'date-fns';
import { v4 as uuid } from 'uuid';
import { Logger } from '@nestjs/common';

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const logger = new Logger();
    try {
      const dirPath = path.join(process.cwd(), 'uploads');
      if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath);
        logger.log(`Directory ${dirPath} has been created!`);
      }
    } catch (e) {
      logger.error(e);
    }
    cb(null, path.join(process.cwd(), 'uploads'));
  },
  filename: function (req, file, cb) {
    const originalname = file.originalname.substring(
      file.originalname.lastIndexOf('.'),
    );
    const uniqueSuffix = `${format(Date.now(), 'yyyy-MM-dd')}-${uuid()}${originalname}`;
    cb(null, uniqueSuffix);
  },
});

export { storage };
